<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />







<meta name="baidu-site-verification" content="VwSJtPrT0X" />









  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,蓝牙," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="官方文档 本文将介绍如何使用传统蓝牙。传统蓝牙适用于电池使用强度较大的操作，例如 Android 设备之间的流式传输和通信等。 针对具有低功耗要求的蓝牙设备，Android 4.3（API 级别 18）中引入了面向低功耗蓝牙的 API 支持。 如需了解更多信息，请参阅低功耗蓝牙。 基础知识本文将介绍如何使用 Android Bluetooth API 来完成使用蓝牙进行通信的四项主要任务：  设置">
<meta name="keywords" content="Android,蓝牙">
<meta property="og:type" content="article">
<meta property="og:title" content="蓝牙开发  传统蓝牙API的使用一、(启用，发现，查找设备)">
<meta property="og:url" content="http://chenzd.cn/2017/10/24/蓝牙开发-传统蓝牙API的使用一、-启用，发现，查找设备/index.html">
<meta property="og:site_name" content="陈明日的博客">
<meta property="og:description" content="官方文档 本文将介绍如何使用传统蓝牙。传统蓝牙适用于电池使用强度较大的操作，例如 Android 设备之间的流式传输和通信等。 针对具有低功耗要求的蓝牙设备，Android 4.3（API 级别 18）中引入了面向低功耗蓝牙的 API 支持。 如需了解更多信息，请参阅低功耗蓝牙。 基础知识本文将介绍如何使用 Android Bluetooth API 来完成使用蓝牙进行通信的四项主要任务：  设置">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-10-24T12:55:55.564Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="蓝牙开发  传统蓝牙API的使用一、(启用，发现，查找设备)">
<meta name="twitter:description" content="官方文档 本文将介绍如何使用传统蓝牙。传统蓝牙适用于电池使用强度较大的操作，例如 Android 设备之间的流式传输和通信等。 针对具有低功耗要求的蓝牙设备，Android 4.3（API 级别 18）中引入了面向低功耗蓝牙的 API 支持。 如需了解更多信息，请参阅低功耗蓝牙。 基础知识本文将介绍如何使用 Android Bluetooth API 来完成使用蓝牙进行通信的四项主要任务：  设置">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://chenzd.cn/2017/10/24/蓝牙开发-传统蓝牙API的使用一、-启用，发现，查找设备/"/>





  <title>蓝牙开发  传统蓝牙API的使用一、(启用，发现，查找设备) | 陈明日的博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">陈明日的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">好记性不如烂笔头~</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://chenzd.cn/2017/10/24/蓝牙开发-传统蓝牙API的使用一、-启用，发现，查找设备/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chenzaidong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/title.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="陈明日的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">蓝牙开发  传统蓝牙API的使用一、(启用，发现，查找设备)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-24T20:51:22+08:00">
                2017-10-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/Android-学习笔记/" itemprop="url" rel="index">
                    <span itemprop="name">Android 学习笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/10/24/蓝牙开发-传统蓝牙API的使用一、-启用，发现，查找设备/" class="leancloud_visitors" data-flag-title="蓝牙开发  传统蓝牙API的使用一、(启用，发现，查找设备)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><a href="https://developer.android.google.cn/guide/topics/connectivity/bluetooth.html#TheBasics" target="_blank" rel="external">官方文档</a></p>
<p>本文将介绍如何使用传统蓝牙。传统蓝牙适用于电池使用强度较大的操作，例如 Android 设备之间的流式传输和通信等。 针对具有低功耗要求的蓝牙设备，Android 4.3（API 级别 18）中引入了面向低功耗蓝牙的 API 支持。 如需了解更多信息，请参阅<a href="https://developer.android.google.cn/guide/topics/connectivity/bluetooth-le.html" target="_blank" rel="external">低功耗蓝牙</a>。</p>
<h2 id="基础知识"><a href="#基础知识" class="headerlink" title="基础知识"></a>基础知识</h2><p>本文将介绍如何使用 Android Bluetooth API 来完成使用蓝牙进行通信的四项主要任务：</p>
<ol>
<li>设置蓝牙</li>
<li>查找局部区域内的配对设备或可用设备</li>
<li>连接设备</li>
<li>设备之间传输数据。</li>
</ol>
<a id="more"></a>
<p><a href="https://developer.android.google.cn/reference/android/bluetooth/package-summary.html" target="_blank" rel="external">android.bluetooth</a> 包中提供了所有 Bluetooth API。 下面概要列出了创建蓝牙连接所需的类和接口：</p>
<ul>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothAdapter.html" target="_blank" rel="external">BluetoothAdapter</a></p>
<p>  表示本地蓝牙适配器（蓝牙无线装置）。 BluetoothAdapter 是所有蓝牙交互的入口点。 利用它可以发现其他蓝牙设备，查询绑定（配对）设备的列表，使用已知的 MAC 地址实例化 BluetoothDevice，以及创建 BluetoothServerSocket 以侦听来自其他设备的通信。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html" target="_blank" rel="external">BluetoothDevice</a></p>
<p>  表示远程蓝牙设备。利用它可以通过 BluetoothSocket 请求与某个远程设备建立连接，或查询有关该设备的信息，例如设备的名称、地址、类和绑定状态等。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothSocket.html" target="_blank" rel="external">BluetoothSocket</a></p>
<p>  表示蓝牙套接字接口（与 TCP Socket 相似）。这是允许应用通过 InputStream 和 OutputStream 与其他蓝牙设备交换数据的连接点。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothClass.html" target="_blank" rel="external">BluetoothClass</a></p>
<p>  描述蓝牙设备的一般特征和功能。 这是一组只读属性，用于定义设备的主要和次要设备类及其服务。 不过，它不能可靠地描述设备支持的所有蓝牙配置文件和服务，而是适合作为设备类型提示。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothProfile.html" target="_blank" rel="external">BluetoothProfile</a></p>
<p>  表示蓝牙配置文件的接口。 <code>蓝牙配置文件</code>是适用于设备间蓝牙通信的无线接口规范。 免提配置文件便是一个示例。 如需了解有关配置文件的详细讨论，请参阅使用<a href="https://developer.android.google.cn/guide/topics/connectivity/bluetooth.html#Profiles" target="_blank" rel="external">配置文件</a></p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothHeadset.html" target="_blank" rel="external">BluetoothHeadset</a></p>
<p>  提供蓝牙耳机支持，以便与手机配合使用。 其中包括蓝牙耳机和免提（1.5 版）配置文件。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothA2dp.html" target="_blank" rel="external">BluetoothA2dp</a></p>
<p>  定义高质量音频如何通过蓝牙连接和流式传输，从一台设备传输到另一台设备。“A2DP”代表高级音频分发配置文件。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothHealth.html" target="_blank" rel="external">BluetoothHealth</a></p>
<p>  表示用于控制蓝牙服务的健康设备配置文件代理。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothHealthCallback.html" target="_blank" rel="external">BluetoothHealthCallback</a></p>
<p>  用于实现 BluetoothHealth 回调的抽象类。您必须扩展此类并实现回调方法，以接收关于应用注册状态和蓝牙通道状态变化的更新内容。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothHealthAppConfiguration.html" target="_blank" rel="external">BluetoothHealthAppConfiguration</a></p>
<p>  表示第三方蓝牙健康应用注册的应用配置，以便与远程蓝牙健康设备通信。</p>
</li>
<li><p><a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothProfile.ServiceListener.html" target="_blank" rel="external">BluetoothProfile.ServiceListener</a></p>
<p>  在 <a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothProfile.html" target="_blank" rel="external">BluetoothProfile</a> IPC 客户端连接到服务（即，运行特定配置文件的内部服务）或断开服务连接时向其发送通知的接口。</p>
</li>
</ul>
<h2 id="蓝牙权限"><a href="#蓝牙权限" class="headerlink" title="蓝牙权限"></a>蓝牙权限</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.BLUETOOTH"</span> /&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.BLUETOOTH_ADMIN "</span> /&gt;</span></div></pre></td></tr></table></figure>
<h2 id="设置蓝牙"><a href="#设置蓝牙" class="headerlink" title="设置蓝牙"></a>设置蓝牙</h2><h3 id="1-获取-BluetoothAdapter"><a href="#1-获取-BluetoothAdapter" class="headerlink" title="1. 获取 BluetoothAdapter"></a>1. 获取 BluetoothAdapter</h3><p>所有蓝牙 Activity 都需要 <code>BluetoothAdapter</code>。 要获取 <code>BluetoothAdapter</code>，请调用静态 <code>getDefaultAdapter()</code> 方法。这将返回一个表示设备自身的蓝牙适配器（蓝牙无线装置）的 <code>BluetoothAdapter</code>。 整个系统有一个蓝牙适配器，并且您的应用可使用此对象与之交互。 如果 <code>getDefaultAdapter()</code> 返回 <code>null</code>，则该设备不支持蓝牙，您的操作到此为止。 例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();</div><div class="line"><span class="keyword">if</span> (mBluetoothAdapter == <span class="keyword">null</span>) &#123;</div><div class="line">    <span class="comment">// 设备不支持，将不执行后续操作</span></div><div class="line">    <span class="keyword">return</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="2-启用蓝牙"><a href="#2-启用蓝牙" class="headerlink" title="2. 启用蓝牙"></a>2. 启用蓝牙</h3><p>在开启蓝牙操作前，调用 <code>isEnabled()</code> 以检查当前是否已启用蓝牙。 如果此方法返回 <code>false</code>，则表示蓝牙处于停用状态。</p>
<p>启用蓝牙有2方式：</p>
<ol>
<li>调用系统activity，然后在回调方法 <code>onActivityResult()</code> 中处理结果，官方文档推荐该方式</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Intent enableBtIntent = <span class="keyword">new</span> Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);</div><div class="line">startActivityForResult(enableBtIntent, REQUEST_CODE);</div></pre></td></tr></table></figure>
<ol>
<li>通过<code>BluetoothAdapter</code>的<a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothAdapter.html#enable(" target="_blank" rel="external">enable()</a>)方法<blockquote>
<p>需要<code>BLUETOOTH_ADMIN</code>权限许可。该<code>enable()</code>方法仅用于包括用于更改系统设置的用户界面的应用程序</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">boolean</span> enable = mBLEAdater.enable();</div></pre></td></tr></table></figure>
</blockquote>
</li>
</ol>
<p>这是一个<code>异步</code>调用：它将立即返回，并且客户端应该监听<code>ACTION_STATE_CHANGED</code> 以获得随后的适配器状态更改的通知。如果此调用返回<code>true</code>，则适配器状态将立即转换<code>STATE_OF</code>F到<code>STATE_TURNING_ON</code>，稍后过渡到任一<code>STATE_OFF</code>或<code>STATE_ON</code>。如果此调用返回<code>false</code>，那么立即出现的问题将阻止适配器打开，例如飞行模式或适配器已打开。</p>
<h3 id="3-监听状态改变的广播"><a href="#3-监听状态改变的广播" class="headerlink" title="3. 监听状态改变的广播"></a>3. 监听状态改变的广播</h3><ul>
<li>蓝牙状态改变的广播字段,每当蓝牙状态发生变化时，系统都会广播此 Intent</li>
</ul>
<blockquote>
<p>BluetoothAdapter.ACTION_STATE_CHANGED</p>
</blockquote>
<p>此广播包含额外字段</p>
<ol>
<li><code>EXTRA_STATE</code>  新的蓝牙状态</li>
<li><p><code>EXTRA_PREVIOUS_STATE</code> 旧的蓝牙状态</p>
<p>这些额外字段可能的值包括 <code>STATE_TURNING_ON</code>、<code>STATE_ON</code>、<code>STATE_TURNING_OFF</code> 和 <code>STATE_OFF</code>。</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 蓝牙状态变化的广播</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> BroadcastReceiver mBleStateChangeBroadcast = <span class="keyword">new</span> BroadcastReceiver() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(Context context, Intent intent)</span> </span>&#123;</div><div class="line">        <span class="keyword">int</span> intExtra = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);</div><div class="line">        </div><div class="line">    &#125;</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<h2 id="查找设备"><a href="#查找设备" class="headerlink" title="查找设备"></a>查找设备</h2><p>使用 <code>BluetoothAdapter</code>，您可以通过设备发现或通过查询配对（绑定）设备的列表来查找远程蓝牙设备。</p>
<p>设备发现是一个扫描过程，它会搜索局部区域内已启用蓝牙功能的设备，然后请求一些关于各台设备的信息（有时也被称为“发现”、“查询”或“扫描”）。但局部区域内的蓝牙设备仅在其当前已启用可检测性时才会响应发现请求。 如果设备可检测到，它将通过共享一些信息（例如设备名称、类及其唯一 MAC 地址）来响应发现请求。 利用此信息，执行发现的设备可以选择发起到被发现设备的连接。</p>
<p>在首次与远程设备建立连接后，将会自动向用户显示配对请求。 设备完成配对后，将会保存关于该设备的基本信息（例如设备名称、类和 MAC 地址），并且可使用 Bluetooth API 读取这些信息。 利用远程设备的已知 MAC 地址可随时向其发起连接，而无需执行发现操作（假定该设备处于有效范围内）。</p>
<p>请记住，被配对与被连接之间存在差别。被配对意味着两台设备知晓彼此的存在，具有可用于身份验证的共享链路密钥，并且能够与彼此建立加密连接。 被连接意味着设备当前共享一个 RFCOMM 通道，并且能够向彼此传输数据。 当前的 Android Bluetooth API 要求对设备进行配对，然后才能建立 RFCOMM 连接。 （在使用 Bluetooth API 发起加密连接时，会自动执行配对）。</p>
<blockquote>
<p>注：Android 设备默认处于不可检测到状态。 用户可通过系统设置将设备设为在有限的时间内处于可检测到状态，或者，应用可请求用户在不离开应用的同时<a href="https://developer.android.google.cn/guide/topics/connectivity/bluetooth.html#EnablingDiscoverability" target="_blank" rel="external">启用可检测性</a>。</p>
</blockquote>
<h3 id="查询配对的设备"><a href="#查询配对的设备" class="headerlink" title="查询配对的设备"></a>查询配对的设备</h3><p>在执行设备发现之前，有必要查询已配对的设备集，以了解所需的设备是否处于已知状态。 为此，请调用 <a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothAdapter.html#getBondedDevices(" target="_blank" rel="external">getBondedDevices()</a>)。 这将返回表示已配对设备的一组 <a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html" target="_blank" rel="external">BluetoothDevice</a>。</p>
<p>官方demo<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">Set&lt;BluetoothDevice&gt; pairedDevices = mBluetoothAdapter.getBondedDevices();</div><div class="line"><span class="comment">// If there are paired devices</span></div><div class="line"><span class="keyword">if</span> (pairedDevices.size() &gt; <span class="number">0</span>) &#123;</div><div class="line">    <span class="comment">// Loop through paired devices</span></div><div class="line">    <span class="keyword">for</span> (BluetoothDevice device : pairedDevices) &#123;</div><div class="line">        <span class="comment">// Add the name and address to an array adapter to show in a ListView</span></div><div class="line">        mArrayAdapter.add(device.getName() + <span class="string">"\n"</span> + device.getAddress());</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>返回的结合也可以转换成ArrayList<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Set&lt;BluetoothDevice&gt; bondedDevices = mBLEAdater.getBondedDevices();</div><div class="line">ArrayList&lt;BluetoothDevice&gt; bluetoothDeviceArrayList = <span class="keyword">new</span> ArrayList&lt;&gt;(bondedDevices);</div></pre></td></tr></table></figure></p>
<h3 id="发现设备"><a href="#发现设备" class="headerlink" title="发现设备"></a>发现设备</h3><p>要开始发现设备，只需调用 <code>startDiscovery()</code>。该进程为异步进程，并且该方法会立即返回一个布尔值，指示是否已成功启动发现操作。 发现进程通常包含约<code>12</code>秒钟的查询扫描，之后对每台发现的设备进行页面扫描，以检索其蓝牙名称。</p>
<p>此处有三个广播可以使用：</p>
<ol>
<li>开启扫描广播</li>
<li>扫描结束广播</li>
<li>发现到设备的广播</li>
</ol>
<h4 id="扫描状态"><a href="#扫描状态" class="headerlink" title="扫描状态"></a>扫描状态</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//注册扫描状态广播监听</span></div><div class="line">IntentFilter filter = <span class="keyword">new</span> IntentFilter();</div><div class="line">filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);</div><div class="line">filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);</div><div class="line">registerReceiver(mDisconverState, filter);</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line"><span class="comment">     * 扫描状态广播</span></div><div class="line"><span class="comment">     */</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> BroadcastReceiver mDisconverState = <span class="keyword">new</span> BroadcastReceiver() &#123;</div><div class="line">        <span class="meta">@Override</span></div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(Context context, Intent intent)</span> </span>&#123;</div><div class="line">            String action = intent.getAction();</div><div class="line">            <span class="keyword">if</span> (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) &#123;</div><div class="line">               <span class="comment">//开始扫描</span></div><div class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) &#123;</div><div class="line">               <span class="comment">//结束扫描</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;;</div></pre></td></tr></table></figure>
<h4 id="发现设备-1"><a href="#发现设备-1" class="headerlink" title="发现设备"></a>发现设备</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Create a BroadcastReceiver for ACTION_FOUND</span></div><div class="line"><span class="keyword">private</span> <span class="keyword">final</span> BroadcastReceiver mReceiver = <span class="keyword">new</span> BroadcastReceiver() &#123;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onReceive</span><span class="params">(Context context, Intent intent)</span> </span>&#123;</div><div class="line">        String action = intent.getAction();</div><div class="line">        <span class="comment">// When discovery finds a device</span></div><div class="line">        <span class="keyword">if</span> (BluetoothDevice.ACTION_FOUND.equals(action)) &#123;</div><div class="line">            <span class="comment">// Get the BluetoothDevice object from the Intent</span></div><div class="line">            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);</div><div class="line">            <span class="comment">// Add the name and address to an array adapter to show in a ListView</span></div><div class="line">            mArrayAdapter.add(device.getName() + <span class="string">"\n"</span> + device.getAddress());</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;;</div><div class="line"><span class="comment">// Register the BroadcastReceiver</span></div><div class="line">IntentFilter filter = <span class="keyword">new</span> IntentFilter(BluetoothDevice.ACTION_FOUND);</div><div class="line">registerReceiver(mReceiver, filter); <span class="comment">// Don't forget to unregister during onDestroy</span></div></pre></td></tr></table></figure>
<blockquote>
<p><em>注意1</em> ：执行设备发现对于蓝牙适配器而言是一个非常繁重的操作过程，并且会消耗大量资源。 在找到要连接的设备后，确保始终使用 <code>cancelDiscovery()</code> 停止发现，然后再尝试连接。 此外，如果您已经保持与某台设备的连接，那么执行发现操作可能会大幅减少可用于该连接的带宽，因此不应该在处于连接状态时执行发现操作。</p>
<p><em>注意2</em> : 发现设备的广播中会多次被调，始终包含额外的字段<a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html#EXTRA_DEVICE" target="_blank" rel="external">EXTRA_DEVICE</a>和<a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html#EXTRA_CLASS" target="_blank" rel="external">EXTRA_CLASS</a>。可以包含额外的字段<a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html#EXTRA_NAME" target="_blank" rel="external">EXTRA_NAME</a>和/或 <a href="https://developer.android.google.cn/reference/android/bluetooth/BluetoothDevice.html#EXTRA_RSSI" target="_blank" rel="external">EXTRA_RSSI</a>可用的。</p>
<p><em>注意3</em> : 同一个设备可能被多次扫描到， 返回的<code>name</code>有可能为空，应该对其进行判断，通过mac表示唯一性</p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
            <a href="/tags/蓝牙/" rel="tag"># 蓝牙</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/20/AIDL的使用/" rel="next" title="AIDL的使用">
                <i class="fa fa-chevron-left"></i> AIDL的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/title.jpg"
              alt="chenzaidong" />
          
            <p class="site-author-name" itemprop="name">chenzaidong</p>
            <p class="site-description motion-element" itemprop="description">有人爱 有事做 有所期待</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/chenzaidong" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#基础知识"><span class="nav-number">1.</span> <span class="nav-text">基础知识</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#蓝牙权限"><span class="nav-number">2.</span> <span class="nav-text">蓝牙权限</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#设置蓝牙"><span class="nav-number">3.</span> <span class="nav-text">设置蓝牙</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-获取-BluetoothAdapter"><span class="nav-number">3.1.</span> <span class="nav-text">1. 获取 BluetoothAdapter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-启用蓝牙"><span class="nav-number">3.2.</span> <span class="nav-text">2. 启用蓝牙</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-监听状态改变的广播"><span class="nav-number">3.3.</span> <span class="nav-text">3. 监听状态改变的广播</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查找设备"><span class="nav-number">4.</span> <span class="nav-text">查找设备</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#查询配对的设备"><span class="nav-number">4.1.</span> <span class="nav-text">查询配对的设备</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#发现设备"><span class="nav-number">4.2.</span> <span class="nav-text">发现设备</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#扫描状态"><span class="nav-number">4.2.1.</span> <span class="nav-text">扫描状态</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#发现设备-1"><span class="nav-number">4.2.2.</span> <span class="nav-text">发现设备</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chenzaidong</span>

  
</div>
<!--

  <div class="powered-by">由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">主题 &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.2</div>

-->

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2144806"></script>
      <!-- UY END -->
    
  





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("FYNUsMEPesJqt3wytETgaIay-gzGzoHsz", "bvkSr2yvSYvCKO3aRdaPnAG6");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
